package tpcar.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tpcar.ejb.Admin;
import tpcar.ejb.AdminPersonne;
import tpcar.ejb.CarteDeVisite;
import tpcar.ejb.ConsultPersonne;
import tpcar.ejb.Personne;



public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = -1322434790655798901L;


	/**
	 * Lookup the statefull bean used to manage the app 
	 * and gets a reference on it.
	 * @return the bean business interface.
	 * @throws Exception if the bean cannot be retrieved.
	 */
	private Admin getBean() throws Exception {
		Context initialContext = new InitialContext();


		//  with mappedName attribute
		Object o = initialContext.lookup("adminbean");

		if (o instanceof Admin) {
			Admin adminBean = (Admin) o;
			return adminBean;
		}
		else throw new Exception("Cannot cast object into Admin");

	}

	private AdminPersonne getPersonneBean() throws Exception {
		Context initialContext = new InitialContext();


		//  with mappedName attribute
		Object o = initialContext.lookup("AdminPersonneBean");

		if (o instanceof AdminPersonne) {
			AdminPersonne adminPersonneBean = (AdminPersonne) o;
			return adminPersonneBean;
		}
		else throw new Exception("Cannot cast object into AdminPersonne");

	}

	/**
	 * React to a GET request coming from the client. 
	 * Exec the request, print the result.
	 * @throws Exception if the bean cannot be retrieved.
	 */
	protected void doGet ( HttpServletRequest req , HttpServletResponse res)
	throws ServletException , IOException {
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		head(out);
		String type = req.getParameter("type");
		if(type!=null)
		{
			if(type.equals("addCard"))
			{
				String person = req.getParameter("person");
				String nom = person.substring(0,person.lastIndexOf("/"));
				String prenom =person.substring(person.lastIndexOf("/")+1, person.length());
				String email = req.getParameter("email");
				String phone = req.getParameter("phone");
				addCard(nom, prenom, email, phone, out);
			}
			else if(type.equals("addPersonne"))
			{
				String nom = req.getParameter("nom");
				String prenom = req.getParameter("prenom");
				String dateNaissance = req.getParameter("dateNaissance");
				String lieuNaissance = req.getParameter("lieuNaissance");
				String sexe = req.getParameter("sex");
				addPersonne(out, nom, prenom, dateNaissance, lieuNaissance, sexe);
			}
			else if(type.equals("modiftPerson"))
			{
				String person=req.getParameter("person");
				String nom = person.substring(0,person.lastIndexOf("/"));
				String prenom =person.substring(person.lastIndexOf("/")+1, person.length());
				modifyValues(out,nom,prenom);
			}
			else if( type.equals("modifyFinal"))
			{
				String nom = req.getParameter("nom");
				String prenom = req.getParameter("prenom");
				String dateNaissance = req.getParameter("dateNaissance");
				String lieuNaissance = req.getParameter("lieuNaissance");
				String sexe = req.getParameter("sex");
				modifyFinal(out, nom, prenom, dateNaissance, lieuNaissance, sexe);
			}
			else if(type.equals("deletePerson"))
			{
				String person=req.getParameter("person");
				String nom = person.substring(0,person.lastIndexOf("/"));
				String prenom =person.substring(person.lastIndexOf("/")+1, person.length());
				deleteValues(out, nom, prenom);

			}
			else if(type.equals("deleteCard"))
			{
				String person=req.getParameter("person");
				String nom = person.substring(0,person.lastIndexOf("/"));
				String prenom =person.substring(person.lastIndexOf("/")+1, person.length());
				displayCard(out,nom,prenom);
			}
		}
		out.println("<table border=\"2\">");
		out.println("<tr bgcolor=\"#C0C0C0\"><td><h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Add Someone &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h1></td>");
		out.println("<td><h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Add a Card to Someone &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h1></td></tr>");
		out.println("<tr><td>");
		addPersonne(out);
		out.println("</td><td>");
		addCard(out);
		out.println("</td></tr>");
		out.println("<tr bgcolor=\"#C0C0C0\"><td><h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Modify Someone &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h1></td>");
		out.println("<td><h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Delete Someone &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h1></td></tr>");
		out.println("<tr height=\"180px\".><td>");
		modifyPerson(out);
		out.println("</td><td>");
		deletePerson(out);
		out.println("</td></tr>");
		out.println("<tr><td>");
		deleteCard(out);
		out.println("</td></tr>");
		out.println("</table>");

		foot(out);
	}

	//*****************************************************
	//                                     Gui                                                //
	//*****************************************************
	/**
	 * print the admin gui
	 */
	private void head(PrintWriter out) {
		out.println("<html><head><title>Administrator Interface</title></head>");
		out.println("<body>");
	}


	/**
	 * print the admin gui
	 */
	private void foot( PrintWriter out ) {
		out.println("</body >");
		out.println("</html >");
		out.close();
	}


	//****************************************************
	//                             CardManagement                                 //
	//****************************************************


	/**
	 * Add the given card using the card bean.
	 * The card has to bee related
	 */
	private void addCard(String nom, String prenom, String email, String phone, PrintWriter out) {
		if (nom == null ||prenom == null || ((String) nom).length() ==0 || ((String) prenom).length() ==0) {
			out.println("You must enter a last name and a first name!");
			return ;
		}
		//		Initializing context

		try {
			Admin admin = getBean();
			if (admin.addCarteDeVisite(nom, prenom, email, phone)) {
				out.println("<h2> Card added !</h2>");
			} else {
				out.println("<h2> Card was not added !</h2>");
			}
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the CardAdministrator in addCard !</h3>");
			out.println(e + "<br/>");
			return ;
		}
	}


	/**
	 * Get parameters to add a card to a specific person
	 * @param out
	 */
	private void addCard(PrintWriter out) {
		List<Personne> result = null ;
		try {
			ConsultPersonne consult = getConsultPersonBean();
			result = consult.listerTous();
			if(result==null || result.size() == 0){
				out.println("<h3> No one in the database!</h3>");
				return ;
			}
			out.println("<form method =\"get\">");
			out.println(" Person:&nbsp;" + "<select name=\"person\">");
			for (Iterator<Personne> iterator = result.iterator(); iterator.hasNext();) {
				Personne personne = (Personne) iterator.next();
				out.println(" <option value=\""+personne.getNom()+"/"+personne.getPrenom()+"\">"+personne.getNom()+" "+personne.getPrenom()+"</option>");
			}
			out.println("</select>");
			out.println("<br/> E-Mail:&nbsp;" + "<input type=\"text\" name=\"email\"/>");
			out.println("<br/> Phone:&nbsp;" + "<input type=\"text\" name=\"phone\"/>");
			out.println("<br/><input type=\"submit\" value =\"Add it !\"/>");
			out.println("<input type=\"hidden\" name=\"type\" value=\"addCard\"");
			out.println("</form >");
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the ConsultPerson!</h3>");
			out.println(e + "<br/>");
			e.printStackTrace(out);
			return ;
		}

	}

	//****************************************************
	//                           PersonnManagement                               //
	//****************************************************



	/**
	 * *Add a person in the database using the personneBean
	 * @param out
	 * @param nom
	 * @param prenom
	 * @param dateNaissance
	 * @param lieuNaissance
	 * @param sexe
	 */
	private void addPersonne(PrintWriter out,String nom, String prenom, String dateNaissance,
			String lieuNaissance, String sexe) {
		if (nom == null ||prenom == null || ((String) nom).length() ==0 || ((String) prenom).length() ==0) {
			out.println("You must enter a name !");
			return ;
		}
		//		Initializing context

		try {
			AdminPersonne adminPersonne = getPersonneBean();
			if (adminPersonne.addPersonne(nom, prenom, dateNaissance, lieuNaissance,sexe)) {
				out.println("<h2> Person added !</h2>");
			} else {
				out.println("<h2> Person was not added !</h2>");
			}
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the PersonAdministrator in addPersonne!</h3>");
			out.println(e + "<br/>");
			return ;
		}
	}
	
	/**
	 * Print inputs to add someone
	 * @param out
	 */
	private void addPersonne(PrintWriter out)
	{
		out.println("<form method =\"get\">");
		out.println("<p>");
		out.println(" LastName:&nbsp;" + "<input type=\"text\" name=\"nom\"/>");
		out.println("<br/> FirstName:&nbsp;" + "<input type=\"text\" name=\"prenom\"/>");
		out.println("<br/> Date of Birth:&nbsp;" + "<input type=\"text\" name=\"dateNaissance\"/>");
		out.println("<br/> Place of brith:&nbsp;" + "<input type=\"text\" name=\"lieuNaissance\"/>");
		out.println("<br/> Gender:&nbsp;");
		out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"woman\">woman");
		out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"man\">man<BR>");
		out.println("<input type=\"hidden\" name=\"type\" value=\"addPersonne\"");

		out.println("<br/><input type=\"submit\" value =\"Add it !\"/>");
		out.println("</p>");
		out.println("</form >");
	} 

	/**
	 * Print selection menu to modify a person
	 * @param out
	 */
	private void modifyPerson(PrintWriter out) {
		List<Personne> result = null ;
		try {
			ConsultPersonne consult = getConsultPersonBean();
			result = consult.listerTous();
			if(result==null || result.size() == 0){
				out.println("<h3> No one to be modified</h3>");
				return ;
			}
			out.println("<form method =\"get\">");
			out.println("<p>");
			out.println(" Person:&nbsp;" + "<select name=\"person\">");
			for (Iterator<Personne> iterator = result.iterator(); iterator.hasNext();) {
				Personne personne = (Personne) iterator.next();
				out.println(" <option value=\""+personne.getNom()+"/"+personne.getPrenom()+"\">"+personne.getNom()+" "+personne.getPrenom()+"</option>");
			}
			out.println("</select>");
			out.println("<br/><input type=\"submit\" value =\"Modify !\"/>");
			out.println("<input type=\"hidden\" name=\"type\" value=\"modiftPerson\"");
			out.println("</p>");
			out.println("</form >");
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the ConsultPerson in modifyPerson</h3>");
			out.println(e + "<br/>");
			e.printStackTrace(out);
			return ;
		}

	}

	/**
	 * Print inputs to modify someone
	 * @param out
	 * @param nom
	 * @param prenom
	 */
	private void modifyValues(PrintWriter out,String nom,String prenom)
	{
		try
		{
			AdminPersonne admin = getAdminPersonBean();
			Personne person = admin.getPersonne(nom, prenom);
			if(person == null)
				return ;
			out.println("<table border=\"2\"><tr bgcolor=\"#C0C0C0\"><td>");
			out.println("<h1>Modify "+person.getNom() +" "+person.getPrenom() +"</h1></td></tr><tr><td>");
			out.println("<form method =\"get\">");
			out.println("<p>");
			out.println("<input type=\"hidden\" name=\"nom\" value=\""+nom+"\"");
			out.println("<input type=\"hidden\" name=\"prenom\" value=\""+prenom+"\"");
			out.println("<br/> Date of Birth:&nbsp;" + "<input type=\"text\" name=\"dateNaissance\" value=\""+person.getDateNaissance()+"\"/>");
			out.println("<br/> Place of brith:&nbsp;" + "<input type=\"text\" name=\"lieuNaissance\" value=\""+person.getLieuNaissance()+"\"/>");
			out.println("<br/> Gender:&nbsp;");
			if(person.getSexe() != null && person.getSexe().equals("woman"))
			{
				out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"woman\" checked=\"checked\">woman");
				out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"man\">man<BR>");
			}
			else if(person.getSexe() != null && person.getSexe().equals("man"))
			{
				out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"woman\" >woman");
				out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"man\" checked=\"checked\">man<BR>");
			}else
			{
				out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"woman\" >woman");
				out.println("<INPUT TYPE=RADIO NAME=\"sex\" VALUE=\"man\" >man<BR>");
			}

			out.println("<input type=\"hidden\" name=\"type\" value=\"modifyFinal\"");

			out.println("<br/><input type=\"submit\" value =\"Validate modification !\"/>");
			out.println("</p>");
			out.println("</form >");
			out.println("</td></tr></table>");
		}catch(Exception e)
		{
			out.println("Exception in modifyValues " + e);
		}
	} 
	
	private void modifyFinal(PrintWriter out, String nom, String prenom, String dateNaissance, String lieuNaissance, String sexe)
	{
		try{
			AdminPersonne admin = getAdminPersonBean();
			admin.modifyPersonne(nom, prenom, dateNaissance, lieuNaissance, sexe);
			out.println("<h1>Modification done</h1>");
		}
		catch(Exception e)
		{
			out.println("Could not modify " + nom +" " + prenom);
			e.printStackTrace(out);
		}
		
	}
	
	/**
	 * Print selection menu to delete a person
	 * @param out
	 */
	private void deletePerson(PrintWriter out) {
		List<Personne> result = null ;
		try {
			ConsultPersonne consult = getConsultPersonBean();
			result = consult.listerTous();
			if(result==null || result.size() == 0){
				out.println("<h3> No one to be deleted</h3>");
				return ;
			}
			out.println("<form method =\"get\">");
			out.println("<p>");
			out.println(" Person:&nbsp;" + "<select name=\"person\">");
			for (Iterator<Personne> iterator = result.iterator(); iterator.hasNext();) {
				Personne personne = (Personne) iterator.next();
				out.println(" <option value=\""+personne.getNom()+"/"+personne.getPrenom()+"\">"+personne.getNom()+" "+personne.getPrenom()+"</option>");
			}
			out.println("</select>");
			out.println("<br/><input type=\"submit\" value =\"Delete !\"/>");
			out.println("<input type=\"hidden\" name=\"type\" value=\"deletePerson\"");
			out.println("</p>");
			out.println("</form >");
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the ConsultPerson in deletePerson</h3>");
			out.println(e + "<br/>");
			e.printStackTrace(out);
			return ;
		}

	}

	/**
	 * Delete person in the database
	 * @param out
	 * @param nom
	 * @param prenom
	 */
	private void deleteValues(PrintWriter out, String nom, String prenom)
	{
		try{
			AdminPersonne admin = getAdminPersonBean();
			if(admin.removePersonne(nom,prenom))
				out.println("<h1>Person deleted</h1>");
			else
				out.println("Could not delete " + nom +" " + prenom);				
		}
		catch(Exception e)
		{
			out.println("Could not delete " + nom +" " + prenom);
			e.printStackTrace(out);
		}
	}

	/**
	 * Display people who have card recorded
	 * @param out
	 */
	private void deleteCard(PrintWriter out)
	{
		List<Personne> result = null ;
		try {
			ConsultPersonne consult = getConsultPersonBean();
			result = consult.listerTous();
			if(result==null || result.size() == 0){
				out.println("<h3> No card to be deleted</h3>");
				return ;
			}
			out.println("<h1>Delete Card</h1><br>");
			out.println("<form method =\"get\">");
			out.println("<p>");
			out.println(" Person:&nbsp;" + "<select name=\"person\">");
			int i =0;
			for (Iterator<Personne> iterator = result.iterator(); iterator.hasNext();) {
				Personne personne = (Personne) iterator.next();
			//	out.println("---- " + personne.getNom() + " ---- " + personne.getCarteDeVisite().size());
		//		if(personne.getCarteDeVisite().size() != 0)
					{
						out.println(" <option value=\""+personne.getNom()+"/"+personne.getPrenom()+"\">"+personne.getNom()+" "+personne.getPrenom()+"</option>");
						i++;
					}
			}
			out.println("</select>");
			if(i==0)
				out.println("<h1>No one has card attached</h1>");
			out.println("<br/><input type=\"submit\" value =\"Delete !\"/>");
			out.println("<input type=\"hidden\" name=\"type\" value=\"deleteCard\"");
			out.println("</p>");
			out.println("</form >");
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the ConsultPerson in deleteCard</h3>");
			out.println(e + "<br/>");
			e.printStackTrace(out);
			return ;
		}
	}
	
	private void displayCard(PrintWriter out, String nom, String prenom)
	{
		try{
			AdminPersonne admin = getAdminPersonBean();
			Personne person = admin.getPersonne(nom, prenom);
			if(person == null)
				{
					out.println("<error, person was not found");
					return;
				}
			Collection <CarteDeVisite> cartes =person.getCarteDeVisite();
			cartes.size();
			out.println("OKKK ");
		}
		catch(Exception e)
		{
			out.println("Could not delete " + nom +" " + prenom);
			e.printStackTrace(out);
		}
	}



	//**********************************************
	//                     Internals Methods                              //
	//**********************************************

	/**
	 * Get ConsultPersonneBean
	 */
	private ConsultPersonne getConsultPersonBean() throws Exception {

		Context initialContext = new InitialContext();

		Object o = initialContext.lookup("ConsultPersonneBean");

		if (o instanceof ConsultPersonne) {
			return (ConsultPersonne) o;
		}
		else throw new Exception("Cannot cast object into ConsultPerson");

	}

	/**
	 * Get AdminPersonnBean
	 * @return
	 * @throws Exception
	 */
	private AdminPersonne getAdminPersonBean() throws Exception {

		Context initialContext = new InitialContext();

		Object o = initialContext.lookup("AdminPersonneBean");

		if (o instanceof AdminPersonne) {
			return (AdminPersonne) o;
		}
		else throw new Exception("Cannot cast object into AdminPersonne");

	}



}
